package com.blockmeta.bbs.minemodule.activity;

import android.content.Context;
import androidx.core.content.ContextCompat;
import android.text.TextUtils;
import com.blankj.utilcode.util.LogUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.blankj.utilcode.util.SpanUtils;
import com.blockmeta.bbs.baselibrary.utils.SharedPreferenceUtil;
import com.blockmeta.bbs.baselibrary.utils.ToastUtil;
import com.blockmeta.bbs.businesslibrary.base.BaseActivity;
import com.blockmeta.bbs.businesslibrary.constant.Constant;
import com.blockmeta.bbs.businesslibrary.net.pojo.BaseCodeResponse;
import com.blockmeta.bbs.businesslibrary.net.request.ForwardApiRequest;
import com.blockmeta.bbs.businesslibrary.net.retrofit.RetrofitFactory;
import com.blockmeta.bbs.businesslibrary.net.rxjava.CommonSubscriber;
import com.blockmeta.bbs.businesslibrary.net.rxjava.RxUtil;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.businesslibrary.widget.CircleImageView;
import com.blockmeta.bbs.minemodule.R;
import com.blockmeta.bbs.minemodule.R2;
import com.blockmeta.bbs.minemodule.net.ApiServer;
import com.blockmeta.bbs.minemodule.pojo.StatusPOJO;
import com.blockmeta.bbs.minemodule.pojo.UserDevicePOJO;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by author on 2019/5/21.
 * 扫描用户结果页面
 */

public class CaptureUserResultActivity extends BaseActivity {
    @BindView(R2.id.user_icon)
    CircleImageView mUserIcon;
    @BindView(R2.id.user_name)
    TextView mUserName;
    @BindView(R2.id.user_desc)
    TextView mUserDesc;
    @BindView(R2.id.user_login)
    Button mUserLogin;
    @BindView(R2.id.user_cancle)
    Button mUserCancle;
    private Context mContext;
    private String mAuthCode;

    @Override
    protected boolean showTitle() {
        return true;
    }

    @Override
    public View setView() {
        setTitleText("扫描结果");
        mContext = CaptureUserResultActivity.this;
        return LayoutInflater.from(mContext).inflate(R.layout.activity_capture_user_result, null);
    }

    /**
     * 序列化数据
     */
    @Override
    public void initSerilization() {
        mAuthCode = getIntent().getStringExtra(Constant.ONE);
    }

    @Override
    protected void initialize() {
        if (AccountHelper.getUserPhonePOJO() != null && AccountHelper.getUserPhonePOJO().getLogo() != null &&
                    !TextUtils.isEmpty(AccountHelper.getUserPhonePOJO().getLogo())) {
            Glide.with(mContext).load(AccountHelper.getUserPhonePOJO().getLogo())
                    .dontAnimate()
                    .into(mUserIcon);
        } else {
            Glide.with(mContext).load(AccountHelper.getUserPhonePOJO().getLogo())
                    .dontAnimate()
                    .into(mUserIcon);
        }
        mUserName.setText(AccountHelper.getUserPhonePOJO().getUserName());


        //请求平台民称
        initPlatformNet();

    }

    private void initPlatformNet() {
        JSONObject jsonObject = new JSONObject();
        //@Query("authcode") String authcode
        try {
            jsonObject.put("authcode", mAuthCode);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RetrofitFactory.getRetrofit()
                .create(ApiServer.class)
                .achieveUserDeviceInfo(ForwardApiRequest.create(ForwardApiRequest.ApiKey.Achieve_DeviceInfo, jsonObject))
                .compose(this.<BaseCodeResponse<UserDevicePOJO>>bindToLifecycle())
                .compose(RxUtil.<BaseCodeResponse<UserDevicePOJO>>rxSchedulerHelper())
                .compose(RxUtil.<UserDevicePOJO>commonResultByCode())
                .subscribe(new CommonSubscriber<UserDevicePOJO>(mContext) {
                    @Override
                    public void onNext(UserDevicePOJO userDevicePOJO) {
                        mUserDesc.setText(new SpanUtils()
                                                  .append("正在使用趣会账号登录 ")
                                                  .append(userDevicePOJO.name).setForegroundColor(ContextCompat.getColor(mContext, R.color.text_black))
                                                  .append(" ，请确认是否本人操作")
                                                  .create());
                    }
                });
    }

    @OnClick({R2.id.user_login, R2.id.user_cancle})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.user_login) {
            initLoginNet();
        } else if (i == R.id.user_cancle) {
            finish();

        }
    }

    /**
     * 允许登录
     */
    private void initLoginNet() {
        JSONObject jsonObject = new JSONObject();
        //@Query("authcode") String authcode
        try {
            jsonObject.put("uid", AccountHelper.getUid());
            jsonObject.put("authcode", mAuthCode);
            jsonObject.put("token", SharedPreferenceUtil.getString(mContext, Constant.TOKEN, ""));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RetrofitFactory.getRetrofit().create(ApiServer.class)
                .agree3Login(ForwardApiRequest.create(ForwardApiRequest.ApiKey.Bind2ChainNode, jsonObject))
                .compose(this.<BaseCodeResponse<StatusPOJO>>bindToLifecycle())
                .compose(RxUtil.<BaseCodeResponse<StatusPOJO>>rxSchedulerHelper())
                .compose(RxUtil.<StatusPOJO>commonResultByCode())
                .subscribe(new CommonSubscriber<StatusPOJO>(mContext) {
                    @Override
                    public void onNext(StatusPOJO statusPOJO) {
                        LogUtils.v("author", new Gson().toJson(statusPOJO));
                        if (statusPOJO.status) {
                            ToastUtil.show("授权登录成功");
                            finish();
                        } else {
                            ToastUtil.show("授权登录失败");
                        }
                    }
                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        finish();
                    }
                });
    }
}
